package com.prathiba.tictactoe;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class UserPlay {

	private List<Coordinate> coordinates = new ArrayList<Coordinate>();

	public void addCoordinate(Coordinate c) {
		coordinates.add(c);
	}

	public List<Coordinate> getCoordinates() {
		return coordinates;
	}

	public boolean isHorizontalMatch() {
		List<Coordinate> sortedCoordinates = new ArrayList<Coordinate>();
		sortedCoordinates = sort();

		for (Coordinate c : sortedCoordinates) {
			if (coordinates.contains(c.horizontalNext()))
				if (coordinates.contains(c.horizontalNext().horizontalNext()))
					return true;
		}

		return false;
	}

	public boolean isVerticalMatch() {
		List<Coordinate> sortedCoordinates = new ArrayList<Coordinate>();
		sortedCoordinates = sort();

		for (Coordinate c : sortedCoordinates) {
			if (coordinates.contains(c.verticalNext()))
				if (coordinates.contains(c.verticalNext().verticalNext()))
					return true;
		}

		return false;

	}

	public boolean isDiagonalMatch() {

		List<Coordinate> sublist1 = Arrays.asList(new Coordinate(0, 0),
				new Coordinate(1, 1), new Coordinate(2, 2));
		List<Coordinate> sublist2 = Arrays.asList(new Coordinate(2, 0),
				new Coordinate(1, 1), new Coordinate(0, 2));

		if (coordinates.containsAll(sublist1)
				|| coordinates.containsAll(sublist2))
			return true;

		return false;
	}

	public List<Coordinate> sort() {

		int[] xarrint = new int[coordinates.size()];
		Coordinate[] coarr = new Coordinate[coordinates.size()];

		int i = 0;
		for (Coordinate c : coordinates) {
			xarrint[i] = c.toInt();
			i++;

		}
		Arrays.sort(xarrint);

		int p = 0;
		for (int j : xarrint) {
			coarr[p] = Coordinate.value(j);
			p++;
		}

		return Arrays.asList(coarr);
	}

	public boolean gameWon() {
		if (isHorizontalMatch() || isVerticalMatch() || isDiagonalMatch())
			return true;

		return false;
	}

	/*
	 * public boolean gameDraw() {
	 * 
	 * if (isHorizontalMatch() || isVerticalMatch() || isDiagonalMatch()) {
	 * return false; } return true;
	 * 
	 * }
	 */

	public Coordinate split(String string) {
		String[] x = string.split(",");
		Coordinate coord = new Coordinate(Integer.parseInt(x[0]),
				Integer.parseInt(x[1]));
		return coord;
	}
}
